package com.neuedu.service.impl;

import com.alibaba.fastjson2.JSON;
import com.neuedu.core.MyChatMessage;
import com.neuedu.service.*;
import com.neuedu.vo.AiVo;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.service.AiServices;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class InterViewServiceImpl implements InterViewService {
    @Value("${funasrUrl}")
    String funasrUrl;
    @Resource
    AiServiceCommonImpl AiCommon;
    @Resource
    VoiceService voiceService;
    @Resource
    MinioService minioService;
    @Resource
    QwenChatModel chatModel;
    @Resource
    InterviewRecordService interviewRecordService;
    @Resource(name = "wyredistemplate")
    RedisTemplate<String, String> redisTemplate;
    @Value("${minio.url}")
    String url;
    @Override
    public AiVo answer(String sessionId, Long login_id, String message) {

        Assistant assistant = AiCommon.getAssistant(login_id, sessionId);
        String content = assistant.chatMessage(message, "Java实习生");
        String path = voiceService.getVoice(content, String.valueOf(login_id));
        return new AiVo(content, path);
    }

    @Override
    public String getVoice(Long login_id, MultipartFile file, String sessionId) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String audio_url = url + minioService.mianshi(login_id,  file.getInputStream().readAllBytes(), "interview" + login_id);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(5, TimeUnit.MINUTES);
        OkHttpClient client = builder.build();
        RequestBody formBody = new FormBody.Builder()
                .add("url", audio_url)
                .build();
        Request request = new Request.Builder()
                .url(funasrUrl) // 替换为你的API URL
                .post(formBody)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    @Override
    public boolean end(String sessionId, Long login_id) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if (null == interviewRecordService.getRecord(login_id, sessionId)) {
            String bucket = "interview" + login_id;
            minioService.clearBucket(bucket);
            String message = getMyChatMessage(sessionId, login_id);
            System.out.println(message);
            if (StringUtils.isNoneBlank(message)) {
                Assistant assistant = AiServices.create(Assistant.class, chatModel);
                String result = assistant.analyze("这是我的面试结果，请帮我分析。" + message);
                return interviewRecordService.save(login_id, sessionId, message, result);
            }
        }
        return false;
    }
    public String getMyChatMessage(String sessionId, Long login_id) {
        String key = login_id + "::" + sessionId;
        if (redisTemplate.hasKey(key)) {
            String str = redisTemplate.opsForValue().get(key);
            List<ChatMessage> list = ChatMessageDeserializer.messagesFromJson(str);
            List<MyChatMessage> myChatMessages = new ArrayList<>();
            if (list.size() > 2) {
                list.remove(0);
                list.remove(0);
            }
            for (ChatMessage chatMessage : list) {
                if (chatMessage instanceof AiMessage message) {
                    myChatMessages.add(new MyChatMessage("ai", message.text()));
                    continue;
                }
                if (chatMessage instanceof UserMessage message) {
                    myChatMessages.add(new MyChatMessage("user", message.singleText()));
                }
            }
            redisTemplate.delete(key);
            if (myChatMessages.size() > 1) {
                return JSON.toJSONString(myChatMessages);
            }
        }
        return null;
    }
}
